import store from '@/store/index.js'
import config from '@/admin.config.js'
const debugOptions = config.navBar.debug

export function httpRequest(path, data = {}, options = {}) {
	return uni.request({
		url: config.server.enable ? config.server.target + path : path,
		data,
		...options
	}).then((res) => {
		// 此处的 res 参数，与使用默认方式调用时 success 回调中的 res 参数一致
		// console.log(res);
		// if (res.statusCode != 200) {
		// 	return Promise.reject(res.data)
		// }
		if (res.statusCode == 200 || res.statusCode == 429) {
			if (res.data.code == 401) {
				// this.$router.push({
				// 	path: config.login.url,
				// });
				uni.reLaunch({
					url: config.login.url
				})
			}
			return Promise.resolve(res.data)
		}

		return Promise.reject(res.data)
	}).catch((err) => {
		// 此处的 err 参数，与使用默认方式调用时 fail 回调中的 err 参数一致
		console.log(err);
	});
}

export function httpGet(path, data = {}, options = {}) {
	return httpRequest(path, data, Object.assign(options, {
		method: "GET",
		header: {
			// 'authorization': "Bearer " + store.state.vuex_token
			'authorization': "Bearer " + uni.getStorageSync("token")
			// 'Content-Type': "application/x-www-form-urlencode"
		}
	}))
}

export function httpPost(path, data = {}, options = {}) {
	return httpRequest(path, data, Object.assign(options, {
		method: "POST",
		header: {
			// 'authorization': "Bearer " + store.state.vuex_token
			'authorization': "Bearer " + uni.getStorageSync("token")
			// 'Content-Type': "application/x-www-form-urlencode"
		}
	}))
}


export function httpPut(path, data = {}, options = {}) {
	return httpRequest(path, data, Object.assign(options, {
		method: "PUT",
		header: {
			// 'authorization': "Bearer " + store.state.vuex_token
			'authorization': "Bearer " + uni.getStorageSync("token")
			// 'Content-Type': "application/x-www-form-urlencode"
		}
	}))
}

export function httpDelete(path, data = {}, options = {}) {
	return httpRequest(path, data, Object.assign(options, {
		method: "DELETE",
		header: {
			// 'authorization': "Bearer " + store.state.vuex_token
			'authorization': "Bearer " + uni.getStorageSync("token")
			// 'Content-Type': "application/x-www-form-urlencode"
		}
	}))
}

// #ifndef VUE3
export function initRequest(Vue) {
	// Vue.prototype.$request = request
	Vue.prototype.$http = {
		get: httpGet,
		post: httpPost,
		put: httpPut,
		delete: httpDelete,
		request: httpRequest
	}
}
// #endif

// #ifdef VUE3
export function initRequest(app) {
	// app.config.globalProperties.$request = request
	app.config.globalProperties.$http = {
		get: httpGet,
		post: httpPost,
		put: httpPut,
		delete: httpDelete,
		request: httpRequest
	}
}
// #endif